//
//  YDAHomeController.m
//  siyanone
//
//  Created by LK-IOS on 2018/3/21.
//  Copyright © 2018年 LK-News. All rights reserved.
//

#import "YDAHomeController.h"
#import "YDAHomeBarView.h"
#import "YDAHomeTopView.h"
#import "YDAHomeTableHeaderView.h"
#import "YDAHomeTableCell.h"
#import "YDAStockRiseFallModel.h"
#import "YDAWeekNewModel.h"
#import "YDHomeMarketModel.h"
#import "YDDayNewsController.h"
#import "YDASearchController.h"

#pragma 跳转新闻详情
#import "YDSingleStockNewsModel.h"
#import "YDVerticalStockNewDetailController.h"
#import "YDStockMarketDetailController.h"
#import "YDVerticalStockBuyController.h"

@interface YDAHomeController ()<UITableViewDataSource , UITableViewDelegate , SYAHomeBarViewDelegate ,SYAHomeTopViewDelegate , SYAHomeTableHeaderViewDelegate>

//tableView
@property (nonatomic , weak) UITableView *tableView;
@property (nonatomic , strong) NSMutableArray *stockRiseFallModelArray;

@property (nonatomic , weak) YDAHomeBarView *barView;

@property (nonatomic , weak) YDAHomeTopView *topView;

//大盘轮播的模型
@property (nonatomic , strong) NSMutableArray *weekNewsModelArray;

@property (nonatomic , strong) NSMutableArray *imageUrlArray;
@property (nonatomic , strong) NSMutableArray *imageTitleArray;
@property (nonatomic , strong) NSMutableArray *marketArray;


@end

@implementation YDAHomeController

-(NSMutableArray *)stockRiseFallModelArray
{
    if (_stockRiseFallModelArray == nil) {
        _stockRiseFallModelArray = [NSMutableArray array];
    }
    return _stockRiseFallModelArray;
}
-(NSMutableArray *)weekNewsModelArray
{
    if (_weekNewsModelArray == nil) {
        _weekNewsModelArray = [NSMutableArray array];
    }
    return _weekNewsModelArray;
}
-(NSMutableArray *)imageUrlArray
{
    if (_imageUrlArray == nil) {
        _imageUrlArray = [NSMutableArray array];
    }
    return _imageUrlArray;
}
-(NSMutableArray *)imageTitleArray
{
    if (_imageTitleArray == nil) {
        _imageTitleArray = [NSMutableArray array];
    }
    return _imageTitleArray;
}
-(NSMutableArray *)marketArray
{
    if (_marketArray == nil) {
        _marketArray = [NSMutableArray array];
    }
    return _marketArray;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    self.view.backgroundColor = [UIColor colorWithHexString:mainGray];
    [self tableView];
    [self setUpDataManger];
    [self barView];
    [self topView];
    
    [self reslveStoreData];
    
    [self loadData];
}

-(void)setUpDataManger
{
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadData)];
    header.lastUpdatedTimeLabel.hidden = NO;//是否隐藏最后一次刷新时间
    header.stateLabel.hidden = NO;//是否隐藏刷新状
    self.tableView.mj_header = header;
}

-(void)loadData
{
    [self loadStockRiseFallData];
    [self loadCarselData];
    [self loadMarketData];
}
#pragma 加载股票涨跌数据
-(void)loadStockRiseFallData
{
    [[SYProgressHUD sharedInstance] showMBHudWithSting:@"加载中..."];
    //沪市大盘股票涨跌榜
    NSString *url = [NSString stringWithFormat:@"/stock/%@/ranking?rankType=%@&size=%@" , @"1A0001" , [NSNumber numberWithInteger:1] , [NSNumber numberWithInteger:50]];
    //rankType
    //size
    
    NSString *baseUrl = [NSString stringWithFormat:@"%@%@",baseUrlHttp , url];
    NSString *authToken = [[SYUserDataManger sharedInstance] getUserToken];
    
    BaseNetRequest *request = [[BaseNetRequest alloc] initWithRequestMethod:GETMethod];
    [request sessionRequestWithDictionary:nil andURLString:baseUrl andAuthToken:authToken WithSuccessBlock:^(NSDictionary *resultDict) {
        DDLog(@"resultDict = %@" , resultDict)
        [[SYProgressHUD sharedInstance] dismissMBWithTime:0];
        [self.tableView.mj_header endRefreshing];
        if ([resultDict[@"code"] integerValue] == 200) {
            [self.stockRiseFallModelArray removeAllObjects];
            
            self.stockRiseFallModelArray = [YDAStockRiseFallModel mj_objectArrayWithKeyValuesArray:resultDict[@"result"]];
            
            [self restoreHomeDataWithDataKey:kongkestoreHomeStockListDataID dataDict:resultDict[@"result"]];
            
            [self.tableView reloadData];
            
        }else{
            [[NavTipsView defaultTipsView] showTipsBannerInView:self.view WithType:NavTipsViewTypeMessage text:@"涨跌榜数据加载出错" isExistNav:YES];
        }
        
    } failBlock:^(NSError *error) {
        [[SYProgressHUD sharedInstance] dismissMBWithTime:0];
        [self.tableView.mj_header endRefreshing];
        DDLog(@"error = %@" , error)
        [[NavTipsView defaultTipsView] showTipsBannerInView:self.view WithType:NavTipsViewTypeMessage text:@"涨跌榜数据加载出错" isExistNav:YES];
    }];
}
#pragma 加载轮播数据
-(void)loadCarselData
{
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:@(0) forKey:@"page"];
    [dict setObject:@(20) forKey:@"size"];
    [BaseNetRequest sessionRequestWithparameters:dict method:GETMethod requstType:WeekNews WithSuccessBlock:^(NSDictionary *resultDict) {
        if ([resultDict[@"code"] integerValue] == 200) {
            
            [self.weekNewsModelArray removeAllObjects];
            self.weekNewsModelArray = [YDAWeekNewModel mj_objectArrayWithKeyValuesArray:resultDict[@"data"]];
            
            [self restoreHomeDataWithDataKey:kongkestoreHomeCarselDataID dataDict:resultDict[@"data"]];
            
            
            [self resloveCarselData];
            
        }else{
        }
    } failBlock:^(NSError *error) {

    }];
}
#pragma 加载大盘数据
-(void)loadMarketData
{
    [BaseNetRequest sessionRequestWithparameters:nil method:GETMethod requstType:GetHomeTopData WithSuccessBlock:^(NSDictionary *resultDict) {
        if ([resultDict[@"code"] integerValue] == 200) {
            [self.marketArray removeAllObjects];
            self.marketArray = [YDHomeMarketModel mj_objectArrayWithKeyValuesArray:resultDict[@"result"][@"stockMarketIndexList"]];
            
            //存储一下数据
            [self restoreHomeDataWithDataKey:kongkestoreHomeMarketDataID dataDict:resultDict[@"result"]];
            
            if (_topView) {
                self.topView.marketModelArray = self.marketArray;
            }else{
                [self topView];
            }
            
        }else{
            
        }
    } failBlock:^(NSError *error) {
    }];
}

-(void)resloveCarselData
{
    if (self.weekNewsModelArray.count && self.weekNewsModelArray.count >= 10) {
        [self.imageUrlArray removeAllObjects];
        [self.imageTitleArray removeAllObjects];
        
        for (int i = 0; i < 5; i++) {
            YDAWeekNewModel *model = self.weekNewsModelArray[i];
            [self.imageTitleArray addObject:model.title];
            [self.imageUrlArray addObject:model.coverUrl];
        }
        
    }
    
    if (_topView) {
        self.topView.imageTitleArray = self.imageTitleArray;
        self.topView.carsoulImageUrlArray = self.imageUrlArray;
    }else{
        [self topView];
    }
}

#pragma  tableView
-(UITableView *)tableView
{
    if (_tableView == nil) {
        UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, LKScreenW, self.view.height - self.tabBarController.tabBar.height) style:UITableViewStyleGrouped];
        [self.view addSubview:tableView];
        tableView.backgroundColor = [UIColor colorWithHexString:mainGray];
        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        tableView.dataSource = self;
        tableView.delegate = self;
        tableView.estimatedRowHeight = 0;
        tableView.estimatedSectionFooterHeight = 0;
        tableView.estimatedSectionHeaderHeight = 0;
        if (isIos11) {
            tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
        _tableView = tableView;
    }
    return _tableView;
}
-(YDAHomeBarView *)barView
{
    if (_barView == nil) {
        YDAHomeBarView *barView = [[YDAHomeBarView alloc] init];
        [self.view addSubview:barView];
        barView.delegate = self;
        [barView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(self.view);
            make.left.right.equalTo(self.view);
            make.top.equalTo(self.view);
            if (isPhoneX) {
                make.height.equalTo(@88);
            }else{
                make.height.equalTo(@64);
            }
        }];
        _barView = barView;
    }
    return _barView;
}
-(YDAHomeTopView *)topView
{
    if (_topView == nil) {
        YDAHomeTopView *topView = [YDAHomeTopView homeTopViewWithCarsoulImageUrlArray:self.imageUrlArray ImageTitleArray:self.imageTitleArray MarketModelArray:self.marketArray];
        
        CGRect topViewFrame;
        if (isPhoneX) {
            topViewFrame = CGRectMake(0, 0, LKScreenW, rateX812(295));
        }else{
            topViewFrame = CGRectMake(0, 0, LKScreenW, rate750(295));
        }
        topView.frame = topViewFrame;
        topView.y = -topView.height;
        topView.delegate = self;
        self.tableView.tableHeaderView = topView;
        _topView = topView;
    }
    return _topView;
}
#pragma SYAHomeBarViewDelegate
-(void)homeTopBarView:(YDAHomeBarView *)topBarView buttonCLick:(SYNoHeightedButton *)button
{
    if (button.tag == 1) {//客服
        NSMutableString* str=[[NSMutableString alloc] initWithFormat:@"telprompt://%@",CustomerPhone];
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
    }
}
//搜索界面
-(void)homeTopBarViewSearchImageCLick:(YDAHomeBarView *)topBarView
{
    YDASearchController *vc = [[YDASearchController alloc] init];
    vc.searchString = @"";
    vc.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:NO];
    
}


-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat defaultH = isPhoneX ? rateX812(210) : rate750(210);
    CGFloat offsetY = scrollView.contentOffset.y;
    
    if (offsetY < 0) {
        self.barView.hidden = YES;
    }else{
        self.barView.hidden = NO;
    }
    CGFloat h = offsetY;
    if (h >= defaultH) {
        h = defaultH;
    }
    CGFloat alpha = 1.0 * offsetY  / 100;
    if (alpha >= 1.0) {
        alpha = 0.99;
    }
    self.barView.backgroundColor = [UIColor colorWithHexString:@"0E4483" alpha:alpha];
}

#pragma SYAHomeTopViewDelegate
-(void)homeTopView:(YDAHomeTopView *)topView didSelectedViewType:(SYAHomeTopViewStyle)viewStyle viewIndex:(NSInteger)index
{
    
    if (viewStyle == SYAHomeTopViewStyleMarket) {//点击大盘
        [self jumpMarketDetailWith:index];
    }else if (viewStyle == SYAHomeTopViewStyleCarsoul){//点击轮播
        [self jumpNewsDetailWithIndex:index];
    }

}
#pragma 挑战到新闻详情页
-(void)jumpNewsDetailWithIndex:(NSInteger)index
{
    
     if (!self.weekNewsModelArray.count)return;
     //数据
     YDAWeekNewModel *newModel = self.weekNewsModelArray[index];
     YDSingleStockNewsModel *singleStockNewsModel = [[YDSingleStockNewsModel alloc] init];
     singleStockNewsModel.createDate = newModel.createTime;
     singleStockNewsModel.title = newModel.title;
     singleStockNewsModel.Id = newModel.Id;
     
     //跳转
     YDVerticalStockNewDetailController *vc = [[YDVerticalStockNewDetailController alloc] init];
     vc.style = NewDetailWeeknews;
     vc.model = singleStockNewsModel;
     vc.hidesBottomBarWhenPushed = YES;
     [self.navigationController pushViewController:vc animated:YES];

}
#pragma 跳转到大盘详情
-(void)jumpMarketDetailWith:(NSInteger)index
{
    if (!self.marketArray.count)return;
    
    for (YDHomeMarketModel *model in self.marketArray) {
        model.isSelected = NO;
    }
    
    YDHomeMarketModel *model = self.marketArray[index];
    model.isSelected = YES;
    YDStockMarketDetailController *vc = [[YDStockMarketDetailController alloc] init];
    vc.hidesBottomBarWhenPushed = YES;
    vc.isNormal = NO;
    vc.marketModelArray = self.marketArray;
    vc.stockName = model.name;
    vc.stockCode = model.code;
    vc.index = index;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma UITableViewDataSource , UITableViewDelegate

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.stockRiseFallModelArray.count;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return isPhoneX ? rateX812(40) : rate750(40);
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return isPhoneX ? rateX812(50) : rate750(50);
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    YDAHomeTableHeaderView *header = [YDAHomeTableHeaderView headerViewWithTableView:tableView];
    header.delegate = self;
    return header;
}
#pragma SYAHomeTableHeaderViewDelegate

-(void)homeTableHeaderView:(YDAHomeTableHeaderView *)headerView didSelectedViewStyle:(SYAHomeTableHeaderViewStyle)viewStyle
{
    if (viewStyle == SYAHomeTableHeaderViewStyleDeafault) {//7*24快讯
        DDLog(@"7*24快讯")
        YDDayNewsController *vc = [[YDDayNewsController alloc] init];
        vc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:vc animated:YES];
    }else if (viewStyle == SYAHomeTableHeaderViewStyleDayNews){//每日要闻
        DDLog(@"每日要闻")
        self.tabBarController.selectedIndex = 1;
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    YDAHomeTableCell *cell = [YDAHomeTableCell cellWithTableView:tableView];
    YDAStockRiseFallModel *model = self.stockRiseFallModelArray[indexPath.row];
    cell.model = model;
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    YDAStockRiseFallModel *model = self.stockRiseFallModelArray[indexPath.row];
    YDVerticalStockBuyController *vc = [[YDVerticalStockBuyController alloc] init];
    vc.isNormal = NO;
    vc.isActivity = NO;
    vc.isPopToRootC = NO;
    vc.stockCode = model.instrumentId;
    vc.stockName = model.name;
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
    
}



//首页数据缓存处理
-(void)restoreHomeDataWithDataKey:(NSString *)dataKey dataDict:(NSDictionary *)dict
{
    dispatch_source_t source = dispatch_source_create(DISPATCH_SOURCE_TYPE_DATA_ADD, 0, 0, dispatch_get_global_queue(0, 0));
    dispatch_resume(source);
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        //获取数据库
        LKKeyValueStore *store = [LKKeyValueStore sharedInstanceWithdbName:kongkepeizidbName];
        if ([store isExistTableWithName:kongkestoreHomeDataKey]) {//存在首页信息表
            [store putObject:dict withId:dataKey intoTable:kongkestoreHomeDataKey];
        }else{//不存在
            [store createTableWithName:kongkestoreHomeDataKey];
            [store putObject:dict withId:dataKey intoTable:kongkestoreHomeDataKey];
        }
        dispatch_source_merge_data(source, 1);
    });
    
}
//获取存储的数据
-(id)getHomeStockDataWithDataId:(NSString *)dataId
{
    //获取数据库
    LKKeyValueStore *store = [LKKeyValueStore sharedInstanceWithdbName:kongkepeizidbName];
    if ([store isExistTableWithName:kongkestoreHomeDataKey]) {//存在首页信息表
        id obj = [store getObjectById:dataId fromTable:kongkestoreHomeDataKey];
        return obj;
    }else{
        return nil;
    }
}

//界面加载，处理缓存数据
-(void)reslveStoreData
{
    [self.marketArray removeAllObjects];
    [self.weekNewsModelArray removeAllObjects];
    [self.stockRiseFallModelArray removeAllObjects];
    
    
    LKKeyValueStore *store = [LKKeyValueStore sharedInstanceWithdbName:kongkepeizidbName];
    if ([store isExistTableWithName:kongkestoreHomeDataKey]) {
        //涨跌榜
        id stockRiseFallObj = [self getHomeStockDataWithDataId:kongkestoreHomeStockListDataID];
        if (stockRiseFallObj) {
            NSArray *stockRiseFallArray = (NSArray *)stockRiseFallObj;
            self.stockRiseFallModelArray = [YDAStockRiseFallModel mj_objectArrayWithKeyValuesArray:stockRiseFallArray];
        }
        //获取大盘数据
        id marketDataObj = [self getHomeStockDataWithDataId:kongkestoreHomeMarketDataID];
        if (marketDataObj) {
            NSDictionary *marketDict = (NSDictionary *)marketDataObj;
            self.marketArray = [YDHomeMarketModel mj_objectArrayWithKeyValuesArray:marketDict[@"stockMarketIndexList"]];
            
        }
        
        //获取轮播数据
        id carselDataObj = [self getHomeStockDataWithDataId:kongkestoreHomeCarselDataID];
        if (carselDataObj) {
            NSArray *carselArray = (NSArray *)carselDataObj;
            self.weekNewsModelArray = [YDAWeekNewModel mj_objectArrayWithKeyValuesArray:carselArray];
            
            [self resloveCarselData];
            
        }
        
        [self.tableView reloadData];
        
        self.topView.marketModelArray = self.marketArray;
        
    }else{//不存在
        return;
    }
}


@end
